import os
from PIL import Image, ImageOps
from werkzeug.utils import secure_filename
import uuid

class ImageProcessor:
    """图片处理工具类"""
    
    ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
    MAX_FILE_SIZE = 10 * 1024 * 1024  # 10MB
    
    @staticmethod
    def is_allowed_file(filename):
        """检查文件类型是否允许"""
        return '.' in filename and \
               filename.rsplit('.', 1)[1].lower() in ImageProcessor.ALLOWED_EXTENSIONS
    
    @staticmethod
    def generate_filename(original_filename):
        """生成安全的文件名"""
        ext = original_filename.rsplit('.', 1)[1].lower()
        return f"{uuid.uuid4().hex}.{ext}"
    
    @staticmethod
    def resize_and_optimize(image_path, max_size=1024, quality=85):
        """调整图片大小并优化"""
        try:
            with Image.open(image_path) as img:
                # 自动旋转（基于EXIF数据）
                img = ImageOps.exif_transpose(img)
                
                # 保持宽高比，限制最大尺寸
                img.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
                
                # 转换为RGB（如果是RGBA或其他模式）
                if img.mode in ('RGBA', 'P'):
                    # 创建白色背景
                    background = Image.new('RGB', img.size, (255, 255, 255))
                    if img.mode == 'P':
                        img = img.convert('RGBA')
                    background.paste(img, mask=img.split()[-1] if img.mode == 'RGBA' else None)
                    img = background
                elif img.mode != 'RGB':
                    img = img.convert('RGB')
                
                # 保存优化后的图片
                img.save(image_path, 'JPEG', quality=quality, optimize=True)
                
                return {
                    'success': True,
                    'width': img.width,
                    'height': img.height,
                    'size': os.path.getsize(image_path)
                }
                
        except Exception as e:
            return {'success': False, 'error': str(e)}
    
    @staticmethod
    def create_thumbnail(image_path, thumbnail_path, size=(200, 200)):
        """创建缩略图"""
        try:
            with Image.open(image_path) as img:
                img = ImageOps.exif_transpose(img)
                img.thumbnail(size, Image.Resampling.LANCZOS)
                
                if img.mode in ('RGBA', 'P'):
                    background = Image.new('RGB', img.size, (255, 255, 255))
                    if img.mode == 'P':
                        img = img.convert('RGBA')
                    background.paste(img, mask=img.split()[-1] if img.mode == 'RGBA' else None)
                    img = background
                
                img.save(thumbnail_path, 'JPEG', quality=80, optimize=True)
                return True
                
        except Exception:
            return False
    
    @staticmethod
    def validate_image(file_path):
        """验证图片文件"""
        try:
            with Image.open(file_path) as img:
                # 验证图片是否损坏
                img.verify()
                
            # 重新打开获取信息（verify后无法再使用）
            with Image.open(file_path) as img:
                width, height = img.size
                
                # 检查图片尺寸
                if width < 50 or height < 50:
                    return {'valid': False, 'error': '图片尺寸太小，最小50x50像素'}
                
                if width > 4096 or height > 4096:
                    return {'valid': False, 'error': '图片尺寸太大，最大4096x4096像素'}
                
                return {
                    'valid': True,
                    'width': width,
                    'height': height,
                    'format': img.format,
                    'mode': img.mode
                }
                
        except Exception as e:
            return {'valid': False, 'error': f'无效的图片文件: {str(e)}'}